﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NetCoreMicroserviceDemo.CommonLib.MessageDto;
using Product.API.Models;

namespace Product.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly ILogger<ProductsController> m_logger;
        private readonly IConfiguration m_Configuration;
        private readonly ICapPublisher m_CapBus;
        private readonly ProductContext m_productContext;

        public ProductsController(ILogger<ProductsController> logger,ProductContext productContext,IConfiguration configuration,ICapPublisher capPublisher)
        {
            m_logger = logger;
            m_productContext = productContext;
            m_Configuration = configuration;
            m_CapBus = capPublisher;
        }

        public IActionResult Get()
        {
            string result = @$"【产品服务】{DateTime.Now:yyyy-MM-dd HH:mm:ss}--" +
                            $"{Request.HttpContext.Connection.LocalIpAddress}:" +
                            $"{Request.HttpContext.Connection.LocalPort}";
            return Ok(result);
        }

        [NonAction]
        [CapSubscribe("order.services.createorder")]

        public async Task ReduceStock(CreateOrderMessageDto createOrderMessageDto)
        {
            m_logger.LogInformation($"ReduceStock: start ProductID {createOrderMessageDto.ProductID} Count:{createOrderMessageDto.Count}");
            var product =   await m_productContext.Products.FindAsync(createOrderMessageDto.ProductID);
            if (product!=null )
            {
                product.Stock -= createOrderMessageDto.Count;
            }
           await   m_productContext.SaveChangesAsync();
        }
    }
}
